package com.tourManagement.service.impl;

import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import cn.hutool.db.handler.BeanHandler;
import com.tourManagement.entity.User;
import com.tourManagement.service.UserService;
import org.springframework.stereotype.Service;

import java.sql.SQLException;
import java.util.List;

/**
 * Author:grass
 * Date:2022/10/16 0016
 */
@Service
public class UserServiceImpl implements UserService {
    //查询所有用户
    @Override
    public List<User> select() throws SQLException {
        return Db.use().findAll(Entity.create("t_user"), User.class);
    }

    //通过用户名或者邮箱查询用户
    @Override
    public User selectByKey(User user) throws SQLException {
        String sql = "";
        String key = "";
        if (user.getUsername() == null && user.getEmail() != null){
            sql = "select * from t_user where email = ?";
            key = user.getEmail();
        }
        if (user.getUsername() != null && user.getEmail() == null){
            sql = "select * from t_user where username = ?";
            key = user.getUsername();
        }
        return Db.use().query(sql, new BeanHandler<>(User.class), key);
    }


    //更新用户信息
    @Override
    public int update(User user) throws SQLException {
        return Db.use().update(Entity.create("t_user").parseBean(user),
                Entity.create("t_user").set("username", user.getUsername()));
    }

    //添加用户
    @Override
    public int insert(User user) throws SQLException {
        return Db.use().insert(Entity.create("t_user").parseBean(user, true, false));
    }

    //删除用户
    @Override
    public int delete(User user) throws SQLException{
        return Db.use().execute("delete from t_user where name = ?",user.getUsername());
    }

}
